class Solution {
public:
    int myAtoi(string str) {
        int res = 0;
        unsigned int i = 0;
        bool sign = true;
        while (i < str.size() && isspace(str[i]))
            i++;
        if (i < str.size() && (str[i] == '+' || str[i] == '-')) {
            if (str[i] == '-')
                sign = false;
            i++;
        }
        while (i < str.size() && isdigit(str[i])) 
        {
            if (sign && ((res > INT_MAX/10) || (res == INT_MAX/10 && str[i]-'0' >= INT_MAX%10)))
                return INT_MAX;
            if (!sign && ((res > -(INT_MIN/10)) || (res == -(INT_MIN/10) && str[i]-'0' >= -(INT_MIN%10))))
                return INT_MIN;
            res = 10*res + (str[i++]-'0');
        }
        if (!sign)
            res *= -1;
        return res;
    }
};
